import $ from 'jquery'

$.fn.grid = function () {
    var $gridHeader = $('<div class="grid-header"></div>');
    var $gridHeaderScroller = $('<div class="grid-header-scroller"></div>')
        .appendTo($gridHeader);
    var $virtualHeaderTable = $('<table border="0" cellpadding="0" cellspacing="0"></table>')
        .appendTo($gridHeaderScroller);
    var $virtualHeader = $('<thead></thead>').appendTo($virtualHeaderTable);
    var $virtualTR = $('<tr></tr>').appendTo($virtualHeader);

    var $srcTable = $('.grid-body table', this);
    var $srcTHs = $('thead th', $srcTable);
    var $colGroup = $srcTable.find('colgroup');
    if ($colGroup.length > 0) {
        $colGroup.remove();
    }

    $colGroup = $('<colgroup></colgroup>');

    $srcTHs.each(function () {
        var $th = $(this);
        var width = $th.attr('width');
        if(width == undefined || width == null)
            width = $th.outerWidth();
            
        var text = $th.text();

       // console.log('width: ', width);
        var $col = $('<col>').appendTo($colGroup);
        $col.width(width);

        var $targetTH = $('<th></th>').appendTo($virtualTR);
        $targetTH.width(width);
        $targetTH.html(text);
    })

    //多加一列
    $('<th></th>').appendTo($virtualTR);
    $('<col>').appendTo($colGroup);

    $colGroup.prependTo($srcTable);
    $gridHeader.prependTo(this);

    var self = this;
    $(window).on('resize', function () {
        var cols = $(".grid-header th", self);
        var cells = $(".grid-body col", self);
        for (var i = 0; i < cols.length - 2; i++) {
            var width = $(cols[i]).css("width");
            $(cells[i]).css("width", width);
        }
    });

    $(".grid-body", this).scroll(function (e) {
        var left = $(this).scrollLeft();
        $(".grid-header-scroller").css({ "margin-left": -left });
    });

    return this;
}